const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors');

//引入token服务
const tokenservice=require('./service/tokenservice')
//引入路由
const index = require('./routes/index')
const User = require('./routes/User')
const GetAccID = require('./routes/GetAccID')
const GetUserSDK = require('./routes/GetUserSDK')
const Upload = require('./routes/Upload')
const Curriculum = require('./routes/Curriculum')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// koa跨域
app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/test') {
            return false;
        }
        return '*';
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', ' X-Requested-With']
}));



/**
 * Token拦截器
 * */
let ex = ['/User/Login','/User/TeacherSendVerification','/UploadNew','/images','/Upload','/RemoveNew'];
app.use(async (ctx, next) => {
    let u = ctx.url;
    let urls = u.split("?");
    let index = ex.indexOf(urls[0]);
    let Token = ctx.request.body.Token || ctx.query.Token;
    let aa = urls[0].indexOf('/data') === -1;
    if (index === -1 && aa) {
        if (Token) {
            try {
                let TokenData={
                    Token:Token
                };
                let TokenRes=await tokenservice.queryUserIdByToken(TokenData);
                if (TokenRes.code=== 1) {
                    ctx.request.body.TeacherUserId=TokenRes.data[0].UserId;
                    await next();
                    return;
                } else {
                    ctx.body = {code: 0, msg: "Token没找到"};
                    return;
                }
            } catch (e) {
                ctx.body = {code: 0, msg: e.message};
                return;
            }
        } else {
            ctx.body = {code: 0, msg: "Token没找到"};
            return;
        }
    }
    await next();
});



// routes
app.use(index.routes(), index.allowedMethods())
app.use(User.routes(), User.allowedMethods())
app.use(GetAccID.routes(), GetAccID.allowedMethods())
app.use(GetUserSDK.routes(), GetUserSDK.allowedMethods())
app.use(Upload.routes(), Upload.allowedMethods())
app.use(Curriculum.routes(), Curriculum.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
